﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RPGXEngine.Networking
{
    public static class NetworkMessageFactory
    {
        #region Public Static Methods

        public static NetworkMessage Create(List<byte> message)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            NetworkMessage m = null;

            int index = 0;
            byte[] bytes = message.ToArray();

            int messageSize = BitConverter.ToInt32(bytes, index);
            index += sizeof(int);

            MessageTypes messageType = (MessageTypes)BitConverter.ToInt32(bytes, index);
            index += sizeof(int);

            switch (messageType)
            {
                case MessageTypes.ConnectToServer:
                    m = new NetworkMessage_ConnectToServer();
                    break;
                case MessageTypes.ConnectToClient:
                    m = new NetworkMessage_ConnectToClient();
                    break;
                case MessageTypes.NewClientConnected:
                    m = new NetworkMessage_NewClientConnected();
                    break;
                case MessageTypes.ClientDisconnected:
                    m = new NetworkMessage_ClientDisconnected();
                    break;
                default:
                    throw new InvalidOperationException(String.Format("'{0}' is an unknown type of '{1}'",
                        messageType,
                        typeof(MessageTypes).Name));
            }

            m.FromBytes(bytes);

            return m;
        }

        #endregion
    }
}
